import { defineStore } from 'pinia'
import service from '@/api'
import { numberKeyboardProps } from 'vant';

export const useUserStore = defineStore('user', {
  state: () => {
    const savedState = JSON.parse(localStorage.getItem('userState') || '{}');
    return {
      id: savedState.id || null,
      name: savedState.name || '',
      number: savedState.number || '',
      clazzId: savedState.clazzId || null,
      isAdmin: savedState.isAdmin || '',
      week: 5,
      day: 1
    }
  },
  getters: {
    currentStudent: (state) => {
      return {
        id: state.id,
        name: state.name,
        number: state.number,
        clazzId: state.clazzId,
        isAdmin: state.isAdmin
      }
    },
    currentTime:(state)=>{
      return {
        week: state.week,
        day: state.day
      }
    }
  },
  actions: {
    login(credentials) {
      let that=this;
      return service.post('/api/students/login', credentials, '登录')
        .then(response => {
          that.id = response.id
          that.name = response.name
          that.number = response.number
          that.clazzId = response.clazzId
          that.isAdmin = response.admin
          localStorage.setItem('token', response.token)
          that.saveState()
          return response
        })
    },
    logout() {
      this.$reset()
      localStorage.removeItem('userState')
      localStorage.removeItem('token')
    },
    saveState() {
      const state = {
        id: this.id,
        name: this.name,
        number: this.number,
        clazzId: this.clazzId,
        isAdmin: this.isAdmin
      }
      localStorage.setItem('userState', JSON.stringify(state))
    }
  }
})